<template>
  <div class="em-container">
    <div class="left">
      <el-input class="searchBtn" v-model="pageParams.keyword" @input="searchEmployee" placeholder="请输入员工姓名进行搜索" prefix-icon="el-icon-search" />
      <!-- 数型控件 -->
      <el-tree ref="treeRef" node-key="id" :data="treeList" :props="defaultProps" default-expand-all highlight-current @current-change="currentChange"></el-tree>
    </div>
    <div class="right">
      <div class="r-top">
        <el-button size="mini" type="danger" @click="$router.push('/employee/detail')">添加员工</el-button>
        <el-button size="mini" @click="dialogVisible = true">excel导入</el-button>
        <el-button size="mini" @click="userExport">excel导出</el-button>
      </div>
      <div class="r-middle">
        <!-- 表单 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span class="username" v-else>{{row?.username.charAt(0)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名">
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable>
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="{row}">
              {{row.formOfEmployment == 1 ? '正式' : '非正式'}}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门">
          </el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          </el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="{row}">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="assignRoleTmp(row)" :loading="row.isLoading">角色</el-button>
              <el-popconfirm title="确定删除吗？" style="margin-left: 10px" @onConfirm="delEmployee(row.id)">
                <el-button slot="reference" type="text"> 删除 </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="r-bottom">
        <!-- 分页 -->
        <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="pageParams.pagesize" @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total,sizes,prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- <importExcel :dialogVisible.sync="dialogVisible" @getUserList="getUserList()" /> -->
    <importExcelTwo v-model="dialogVisible" />

    <el-dialog title="分配权限" :visible.sync="dialogRoleVisible">
      <el-checkbox-group v-model="checkList">
        <el-checkbox :label="item.id" v-for="item in RoleList" :key="item.id">{{item.name}}</el-checkbox>

      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAssignRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getEmployeeRequest, delEmployeeRequest, userExportRequest, getEnabledRoleListRequest, assignRolesRequest, getEmployeeInfoByIdRequest } from "@/api/employee";
import { getDepartmentRequest } from '@/api/department'
//转平铺的树形结构
import { transListToTreeData } from '@/utils'
import _ from "lodash-es";
import FileSaver from 'file-saver'
import importExcel from "./components/importExcel.vue";
import importExcelTwo from "./components/importExcelTwo.vue";
export default {
  name: 'EmployeeCom',
  components: {
    importExcel,
    importExcelTwo,

  },
  data () {
    return {
      total: 0,//分页总数
      tableData: [],//表单数据
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      pageParams: {
        departmentId: 1,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      dialogVisible: false,
      dialogRoleVisible: false,
      checkList: [],
      RoleList: [],//已启用角色列表
      currentId: null,
      roleLoading: false
    }
  },
  computed: {
  },
  created () {
    //搜索添加防抖功能
    this.searchEmployee = _.debounce(this.searchEmployee, 600)
    //获取树状列表
    this.getDepartment()
    //获取员工列表
    this.getUserList()
    //获取-已启用的角色列表
    this.getEnabledRoleList()
  },
  methods: {
    //获取树状列表
    async getDepartment () {
      const res = await getDepartmentRequest()
      //下面这句话,是将treeList数据更新,是异步操作
      this.treeList = transListToTreeData(res.data, 0)
      this.pageParams.departmentId = this.treeList[0].id
      //我们下面操作dom的话要用 $nextTick
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.pageParams.departmentId)
      })
    },
    //获取员工列表
    async getUserList () {
      const res = await getEmployeeRequest(this.pageParams)
      console.log(res)
      this.tableData = res.data.rows
      this.total = res.data.total
      this.tableData.forEach(item => {
        this.$set(item, 'isLoading', false)
      })
    },
    //当前选中节点变化时触发的事件 用来获取当前的id值
    currentChange (a, b) {
      this.pageParams.departmentId = a.id
      this.getUserList()
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.pageParams.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.pageParams.page = val
      this.getUserList()
    },
    //搜索框
    searchEmployee () {
      this.getUserList()
    },
    //删除按钮
    async delEmployee (id) {
      if (this.tableData.length == 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      await delEmployeeRequest(id)
      this.getUserList()
    },
    //userExport导出
    async userExport () {
      const res = await userExportRequest()
      console.log(res)
      //将二进制保存为一个文件
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    //获取-已启用的角色列表
    async getEnabledRoleList () {
      const res = await getEnabledRoleListRequest()
      console.log(res.data)
      this.RoleList = res.data
    },
    async submitAssignRole () {
      await assignRolesRequest({
        id: this.currentId,
        roleIds: this.checkList
      })
      this.dialogRoleVisible = false
    },
    async assignRoleTmp (row) {
      row.isLoading = true
      try {
        this.currentId = row.id
        //发请求,获取这个用户默认有哪些权限,弹出框打开之前自动给他勾选
        const res = await getEmployeeInfoByIdRequest(row.id)
        this.checkList = res.data.roleIds
        this.dialogRoleVisible = true
      } catch (error) {
        //
      } finally {
        row.isLoading = false
      }
    }
  }
}
</script>
<style lang='scss'  scoped>
.em-container {
  padding: 20px;
  display: flex;
  background-color: #f4f5f7;
  // height: 100vh;
  .left {
    padding: 20px;
    flex: 0 1 280px;
    background-color: #fff;
    border-right: 1.5px solid #eaeef4;
    .searchBtn {
      margin-bottom: 10px;
    }
  }
  .right {
    padding: 20px;
    background-color: #fff;
    flex: 1;
    .r-top {
      text-align: right;
    }
    .r-middle {
      margin: 20px 0;
      .username {
        display: block;
        width: 30px;
        height: 30px;
        background-color: rgb(39, 251, 240);
        text-align: center;
        line-height: 30px;
        border-radius: 50%;
        color: #fff;
      }
    }
    .r-bottom {
      text-align: right;
    }
  }
}
</style>
